<?php


namespace service;

use service\HttpService;
use service\SystemConfigService;
use app\admin\model\YilianyunToken;
use think\Url;

class YLYService extends HttpService
{
    protected static $client_id='1040414757';

    protected static $apiKey='9bcb3bd115e9d4601b149ab460c6d5c5';

    protected static $partner='44266';

    protected static $access_token=null;

    protected static $order_id=null;
    /*
     * 获取AccessToken
     *
     * */
    protected static function getAccessToken(){
        $token=YilianyunToken::getToken();
        if(!$token){
            $request=self::postRequest('https://open-api.10ss.net/oauth/oauth',[
                'client_id'=>self::$client_id,
                'grant_type'=>'client_credentials',
                'sign'=>self::generateSign(),
                'scope'=>'all',
                'timestamp'=>time(),
                'id'=>self::create_uuid(),
            ]);
            //返回实例:{
            //  "error":"0",
            //  "error_description":"success",
            //  "body":{
            //      "access_token":"6527c7c8c61948d8812d0e2b9ead4ef2",
            //      "refresh_token":"c531d32db82946789c1d221e1f33bdb4",
            //      "machine_code":"",
            //      "expires_in":2592000,
            //      "scope":"all"
            //   }
            // }
            if($request===false) exception('获取access_token失败');
            try{
                $request=json_decode($request,true);
                if($request['error']==0 && $request['error_description']=='success'){
                    $token=$request['body']['access_token'];
                    YilianyunToken::setToken($token,$request['body']['refresh_token']);
                }
            }catch (\Exception $e){
                exception($e->getMessage());
            }
        }
        return $token;
    }
    /**
     * 生成签名sign
     * @param  array $params 参数
     * @param  string $apiKey API密钥
     * @param  string $msign 打印机密钥
     * @return   string sign
     */
    protected static function generateSign()
    {
        $str=self::$client_id.time().self::$apiKey;
        return strtolower(md5($str));
    }

    //生成UUID4
    protected static function create_uuid() {
        return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',mt_rand( 0, 0xffff ),mt_rand( 0, 0xffff ),mt_rand( 0, 0xffff ),
            mt_rand( 0, 0x0fff )|0x4000,mt_rand( 0, 0x3fff )|0x8000,mt_rand( 0, 0xffff ),mt_rand( 0, 0xffff ),mt_rand( 0, 0xffff ));
    }
    /*
     * 开始打印订单
     * 终端号:$machine_code
     * 打印内容:$content
     * 订单号:$origin_id
     * */
    public static function Printing($machine_code,$content,$origin_id=''){
        $request=self::postRequest('https://open-api.10ss.net/print/index',[
            'client_id'=>self::$client_id,
            'access_token'=>self::getAccessToken(),
            'machine_code'=>$machine_code,
            'content'=>$content,
            'origin_id'=>self::$order_id ? self::$order_id : $origin_id,
            'sign'=>self::generateSign(),
            'id'=>self::create_uuid(),
            'timestamp'=>time()
        ]);
        if($request===false) return false;
        return json_decode($request,true);
    }
    /*
     * 饿了么打印模板
     *
     * */
    public static function ELeMeContent(){
        $count=<<<CONTENT
<FH2><FW2> **#3 饿了么**</FW2></FH2>
................................\r
<FH2><FW2> --在线支付--</FW2></FH2>
<FH><FW> 米尼亚小铁板</FW></FH>\r
下单时间：2017-05-08T10：39：56\r
订单编号：1206479504417779722
***************商品*************\r
<FH><FW> --1号篮子--</FW></FH>\r
<FH><FW>荷包蛋 1 3</FW></FH>\r
<FH><FW>里脊肉 1 8</FW></FH>\r
<FH><FW>铁板黑椒牛柳炒饭-黑椒味 </FW></FH>\r
<FH><FW> 1 18</FW></FH>\r
<FH><FW>培根 1 8</FW></FH>\r
<FH><FW> --其他费用--</FW></FH>\r
<FH><FW>餐盒 1 2</FW></FH>\r
................................\r
<FH><FW>配送费：￥5</FW></FH>\r
<FH><FW>餐盒费：￥2</FW></FH>\r
<FH><FW>小计：￥44</FW></FH>\r
<FH><FW>折扣：￥0</FW></FH>\r
*******************************\r
总价：￥30\r
<FH><FW>红梅小区昌吉路231弄 22号</FW></FH>\r
<FH><FW>102室</FW></FH>\r
<FH><FW>张伟 先生：139-1708-0384</FW></FH>\r
<FH2><FW2> **#3 完 **</FW2></FH2>
CONTENT;
        return $count;

    }
    /*
     * 百度外卖打印模板
     * $name 商家名称,
     * $date 下单时间,
     * $order_info 订单详情,
     * $goods 商品列表
     * 打印模板摘抄与百度外卖
     * */
    public static function BaiduContent($name='',$date='',$order_info=[],$goods=[]){
        if(is_numeric($date)) $date=date('Y年m月d日H时i分',$date);
        try{
            $goodsStr='<table>';
            foreach ($goods as $item){
                $goodsStr.='<tr>';
                $goodsStr.='<td>'.$item['store_name'].'</td><td>X'.$item['cart_num'].'</td><td>'.$item['total_price']."</td>";
                $goodsStr.='</tr>';
            }
            $goodsStr.='</table>';
            self::$order_id=$order_info['order_id'];
            $count=<<<CONTENT
<FH2><FW2> ** {$name} **</FW2></FH2>\r
<FH2><FW2>----在线支付----</FW2></FH2>\r
<FH></FH>\r
下单时间：{$date}\r
订单编号：{$order_info['order_id']}\r
*************商品***************\r
<FH><FW>{$goodsStr}</FW></FH>
................................\r
配送费：￥{$order_info['dispatching_price']}\r
餐盒费：￥{$order_info['lunchbox_price']}\r
********************************<FH>
订单总价：￥{$order_info['total_price']}\r
{$order_info['user_address']}\r
{$order_info['real_name']}：{$order_info['user_phone']}\r
订单备注：{$order_info['mark']}\r
</FH>
<FS><center> ** 完 **</center></FS>
CONTENT;
            return $count;
        }catch (\Exception $e){
            return false;
        }
    }
    /*
     * 删除授权终端
     * $machine_code 易联云打印机终端号
     * */
    public static function Deleteprinter($machine_code){
        $request=self::postRequest('https://open-api.10ss.net/printer/deleteprinter',[
            'client_id'=>self::$client_id,
            'access_token'=>self::getAccessToken(),
            'machine_code'=>$machine_code,
            'sign'=>self::generateSign(),
            'id'=>self::create_uuid(),
            'timestamp'=>time(),
        ]);
        if($request===false) return false;
        return json_decode($request,true);
    }
}